import 'package:contacts_service/contacts_service.dart';
import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/business/mine/model/share_model.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/routers/routers.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pinyin/pinyin.dart';

class ShareMotoController extends BaseController {
  MotoModel model = MotoModel();
  List<ShareModel> shareList = [];
  int total = 0;
  bool saveController = true;
  String phone = '';
  Map<String, List<Contact>> contacts = {};
  List<Contact> haveDatas = [];
  List<Contact> searchDatas = [];
  Contact? selectData;
  Map<String, double> pageData = {};
  ScrollController scrollController = ScrollController();
  bool showShare = false;
  List<String> titles = [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z',
    '#'
  ];
  List<String> allKey = [];
  String keyedNow = '';
  double offsetNow = 0;

  @override
  void onInit() {
    super.onInit();
    debugPrint('share 初始化');
  }

  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onReady() {
    super.onReady();
    debugPrint('当前 share');
    if (saveController) getShareList();
  }

  void getShareList() {
    RequestClient().post<SharePageData>(APIS.shareDeviceList,
        data: {'ebike_id': model.id, 'type': 0}).then((value) {
      if (value != null) {
        debugPrint('分享列表 ---  $value');
        shareList = value.list ?? [];
        total = value.total ?? 0;
      }
      update(['shareList']);
    });
  }

  ///分享点击 0 手机分享 1通讯录分享
  void shareAction(int type) {
    debugPrint('手机号输入');
    switch (type) {
      case 0: //手机号输入
        Get.toNamed(RouteGet.shareInput, arguments: false);
        break;
      case 1: //通讯录跳转
        didGetContacts();
        break;
      default:
    }
  }

  ///获取通讯录跳转
  didGetContacts() async {
    getPermission();
    List<Contact> datas = await ContactsService.getContacts();
    haveDatas = datas;
    contacts = groupData(datas);
    getAllKeys();
    getContactPageData();
    debugPrint('获取通讯录 ---${contacts.length}');
    if (contacts.isNotEmpty) {
      Get.toNamed(RouteGet.shareContacts, arguments: false);
    }
  }

  getAllKeys() {
    allKey = [];
    titles.forEach((element) {
      if (contacts[element] != null) {
        allKey.add(element);
      }
    });
    keyedNow = allKey.first;
  }

  Future<bool> getPermission() async {
    PermissionStatus status = await Permission.contacts.status;
    debugPrint('获取通讯录 ---权限1 -- $status');
    if (status.isDenied) {
      var statused = await Permission.contacts.request();
      debugPrint('获取通讯录 ---权限2 -- $statused');
      if (statused.isGranted) {
        return true;
      }
    }
    return status == PermissionStatus.granted;
  }

  ///通讯录数据处理
  Map<String, List<Contact>> groupData(List<Contact> datas) {
    Map<String, List<Contact>> groupedData = {};
    for (final item in datas) {
      final pinyin = PinyinHelper.getShortPinyin(item.familyName ?? '');
      final letter =
          pinyin.isNotEmpty ? pinyin.substring(0, 1).toUpperCase() : '#';

      if (!groupedData.containsKey(letter)) {
        String lettered = '#';
        if (!titles.contains(letter)) {
          if (!groupedData.containsKey(lettered)) groupedData[lettered] = [];
        } else {
          groupedData[letter] = [];
        }
      }
      if (!titles.contains(letter)) {
        groupedData['#']!.add(item);
      } else {
        groupedData[letter]!.add(item);
      }
    }
    return groupedData;
  }

  void inputFinished(String inputed) {
    phone = inputed;
    if (phone.length != 11) {
      EMILoding.hitLoding('请输入完整手机号'.tr);
    } else {
      Get.toNamed(RouteGet.shareDetails);
    }
  }

  turnNext(Contact data) {
    selectData = data;
    Get.toNamed(RouteGet.shareDetails);
  }

  getContactPageData() {
    double data = 0;
    int index = 0;
    titles.forEach((element) {
      if (contacts[element] != null) {
        if (index == 0) {
          data += 71.sp + 97.sp;
        } else {
          data += 97.sp;
        }
        index++;
        pageData[element] = data;
      }
    });
  }

  didPageScrolling(String string) {
    if (pageData[string] != null) {
      scrollController.animateTo(pageData[string]!,
          duration: const Duration(milliseconds: 100), curve: Curves.easeIn);
    }
  }

  getScrollingKey() {
    scrollController.addListener(() {
      if (scrollController.offset == 0) {
        offsetNow = scrollController.offset;
        keyedNow = allKey.first;
        update(['sidebar']);
      }
      if ((scrollController.offset - offsetNow).abs() < 110.sp) {
        return;
      }

      String keyed = '';
      if (scrollController.offset > offsetNow && scrollController.offset > 0) {
        // debugPrint('列表刷新11 --- $pageData');
        for (var element in titles) {
          if (pageData[element] != null &&
              scrollController.offset < pageData[element]!) {
            // debugPrint(
            //     '列表刷新 --- 000 == ${scrollController.offset}  $keyedNow ==  === $pageData');
            keyed = element;
            if (keyedNow != keyed) {
              keyedNow = keyed;
              // debugPrint(
              //     '列表刷新 --- 11111 == ${scrollController.offset}  $keyedNow ==  === $pageData');
              update(['sidebar']);
              break;
            }
          }
        }
      } else if (scrollController.offset < offsetNow &&
          scrollController.offset > 0) {
        // debugPrint('列表刷新222 ====  ${scrollController.offset} $pageData');
        for (var element in titles.reversed) {
          if (pageData[element] != null &&
              scrollController.offset > pageData[element]!) {
            keyed = element;
            if (keyedNow != keyed) {
              keyedNow = keyed;
              // debugPrint(
              //     '列表刷新 --- 222222 === ${scrollController.offset} $keyedNow $pageData');
              update(['sidebar']);
              break;
            }
          }
        }
      }

      offsetNow = scrollController.offset;
    });
  }

  ///开始搜索
  void searchWithStr(String str) {
    debugPrint('搜索输入 --- $str');
    if (str.isNotEmpty) {
      if (!showShare) {
        showShare = true;
        update();
      }
      fuzzySearch(str);
    } else {
      if (showShare) {
        showShare = false;
        update();
      }
    }
  }

  ///模糊搜索
  void fuzzySearch(String str) {
    final filteredContacts = haveDatas.where((contact) {
      final pinyin =
          PinyinHelper.getPinyinE(contact.displayName ?? '', separator: '');
      final searchStr = PinyinHelper.getPinyinE(str, separator: '');
      debugPrint(
          '模糊搜索 --- $pinyin  == $searchStr --- ${contact.givenName} -- ${contact.displayName} -- ${contact.familyName} -- ${contact.middleName}');
      var type1 = pinyin.toLowerCase().contains(searchStr.toLowerCase());
      var type2 = contact.phones!.isEmpty
          ? false
          : contact.phones!.first.toString().contains(searchStr);

      if (type1) {
        return true;
      } else {
        return type2;
      }
    }).toList();

    searchDatas = filteredContacts;
    debugPrint(
        '模糊搜索2 ${haveDatas.length} ${searchDatas.length} ${filteredContacts.length}');
    update(['searchList']);
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }
}

class ShareMotoBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => ShareMotoController(), fenix: true);
  }
}
